package com.cy.pj.sys.controller;

import com.cy.pj.common.vo.JsonResult;
import com.cy.pj.sys.pojo.Admin;
import com.cy.pj.sys.service.AdminService;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@ResponseBody
public class AdminController {
    @Autowired
    private AdminService adminService;

    @RequestMapping("/admin/page.html")
    public JsonResult getAdminPage(
            // 注意：页面上有可能不提供关键词，要进行适配
            // 在@RequestParam注解中设置defaultValue属性为空字符串表示浏览器不提 供关键词时，keyword 变量赋值为空字符串
            @RequestParam(value="keyword",defaultValue="")String keyword,
            // 浏览器未提供 pageNum 时，默认前往第一页
            @RequestParam(value="pageNum",defaultValue="1")Integer pageNum,
            // 浏览器未提供 pageSize 时，默认每页显示 5 条记录
            @RequestParam(value="pageSize",defaultValue="5")Integer pageSize

            ){
                // 查询得到分页数据
                PageInfo<Admin> pageInfo=adminService.getPageInfo(keyword,pageNum,pageSize);
                // 将分页数据存入模型
                /*modelMap.addAttribute(pageInfo);*/
                 return new JsonResult(pageInfo);
    }
    @RequestMapping("/doDeleteAdminById")
    public JsonResult doDeleteAdminById(Integer[] ids){
        adminService.deleteAdminById(ids);
        return new JsonResult("Delete Ok");
    }

    @RequestMapping("/doSaveAdmin")
    public JsonResult doSaveAdmin(Admin admin){
        adminService.insertAdmin(admin);
        return new JsonResult("Save OK");
    }

    @RequestMapping("doFindAdminById")
    public JsonResult doFindAdminById(Integer id){
        Admin admin = adminService.findAdminById(id);
        return new JsonResult(admin);
    }
    @RequestMapping("/admin/doLogin")
    public JsonResult doLogin(String username,String password){
        //1.获取Subject对象
        Subject subject= SecurityUtils.getSubject();
        //2.通过Subject提交用户信息,交给shiro框架进行认证操作
        //2.1对用户进行封装
        UsernamePasswordToken token= new UsernamePasswordToken(username, password);
//        if(isRememberMe) {
//            token.setRememberMe(true);
//        }
        //2.2对用户信息进行身份认证
        subject.login(token);
        //分析:
        //1)token会传给shiro的SecurityManager
        //2)SecurityManager将token传递给认证管理器
        //3)认证管理器会将token传递给realm
        return new JsonResult("login ok");
    }
}
